const http = require('http')
const Koa = require('koa')
const app = new Koa()
const port = 3000
const puppeteer = require('puppeteer')
const { executablePath } = require('../utils')

const getPageAsync = (url) => {
  return new Promise((resolve, reject) => {
    http.get(url, function (res) {
      var html = ''

      // 这里将会触发data事件，不断触发不断跟新html直至完毕
      res.on('data', function (data) {
        html += data
      })
      // 当数据获取完成将会触发end事件，这里将会打印初菜鸟教程官网的html
      res.on('end', function () {
        // 这里是promise的回调函数，我们通过resolve将获取的html传递下去
        resolve(html)
      })
    }).on('error', function (e) {
      // 如果爬取出错，则通过reject返回
      reject(e)
    })
  })
}

const openBrowser = async () => {
  const browser = await puppeteer.launch({
    headless: true,
    executablePath
  })
  return browser
}

const loadPage = async (url) => {
  const browser = await openBrowser()
  const page = await browser.newPage()
  await page.goto(url, {
    timeout: 60 * 1000
  })
  await page.waitFor(50)
  const content = await page.evaluate(selector => {
    try {
      return document.body.innerHTML
    } catch (e) {
      return null
    }
  }, '')
  await page.close()
  await browser.close()
  return content
}

app.use(async ctx => {
  var url = ctx.query.url
  if (!url) {
    // ctx.body = '请传参url'
    return
  }
  if (!url.startsWith('http://')) {
    url = `http://${url}`
  }
  var body = await getPageAsync(url)
  if (body.startsWith('#include')) {
    body = await loadPage(url)
  }
  body = body.replace(/[\r\n][\r\n]/g, '\n') // 2行->1行
    .replace(/[\r\n][\r\n][\r\n]/g, '\n') // 3行->1行
  ctx.body = body
})

app.listen(port, '0.0.0.0', 0, () => {
  console.log(`Started in http://127.0.0.1:${port}`)
})
